package com.jboost.modules.app.service.strategry.dp;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.jboost.common.util.EncryptSha256Util;
import com.jboost.common.util.HttpRestUtils;
import com.jboost.common.util.JSONUtil;
import com.jboost.modules.app.constant.*;
import com.jboost.modules.app.dto.JdyReq;
import com.jboost.modules.app.dto.XMUserReqDto;
import com.jboost.modules.app.dto.XiHuiPeopleDto;
import com.jboost.modules.app.dto.XinHuiCustomerDto;
import com.jboost.modules.app.service.strategry.common.AbstractJdy;
import com.jboost.modules.app.service.strategry.dp.dto.CustomerFieldsDTO;
import com.jboost.modules.app.service.strategry.dp.dto.DongPingGenJingInfo;
import com.jboost.modules.app.service.strategry.dp.dto.DongPingPeopleDto;
import com.jboost.modules.app.service.strategry.dp.dto.FollowUpRecord;
import com.jboost.modules.system.entity.AJdySyncData;
import com.jboost.modules.system.entity.DpGengJing;
import com.jboost.modules.system.entity.DpKeHu;
import com.jboost.modules.system.mapper.DpGjMapper;
import com.jboost.modules.system.mapper.DpKhMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.compress.utils.Lists;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service(value = "DpCustomerQuery")
@Slf4j
public class DpCustomerQuery extends AbstractJdy<String, DpKeHu, DpKhMapper, DpKeHu> {


    public String getFormId() {
        return "63f0bc0539a1fa000844488c";
    }

    private static String client_id = "4bd568d8dc53feeee63f51085dd00d8ca444ee7525a26af06ba3551f3ffca44cee43a1898d91c1ae";
    private static String client_secret = "11e193f14f848856ab2fec0be5a2b155454e142e96a49402bc162c3e8516ee477975da5991129cb3";

    public HttpHeaders getJdyHeaders(){
        HttpHeaders jdyHeaders = new HttpHeaders();
        jdyHeaders.set("Authorization","Bearer "+ "bdfDElitwqhraWZoCv3uxdv9PysCV605");
        return jdyHeaders;
    }

    public String getAppId() {
        return "64880dc1f3ecc50008fbae61";
    }

    HashMap<String,String> cache = new HashMap<>();


    protected static String getHeader(String scope) throws IOException {
        HashMap<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("grant_type","password");
        paramMap.put("client_id",client_id);
        paramMap.put("client_secret",client_secret);
        paramMap.put("scope",scope);
        paramMap.put("username","icy@dong-pin.com");
        paramMap.put("password", EncryptSha256Util.getSha256Str("DongpinW2025"));
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization","Basic "+ Base64.getEncoder().encodeToString((client_id+":"+client_secret).getBytes()));
        String response = HttpRestUtils.post(tokenUrl, paramMap, headers);
        HashMap hashMap = JSONUtil.fromJson(response, HashMap.class);
        return (String) hashMap.get("access_token");
    };
    @Scheduled(cron = "0 0/55 * * * ?")
    public BaseResult<Boolean> invokeStrategy() throws Exception {
        log.info("开始批量查询客户数据");
        String header = getHeader("company");
        List<String> ids = Lists.newArrayList();
        cache.clear();
        queryAndPush(header, 1, ids);
        List<DpKeHu> sysUserDeparts = baseMapper.selectList(Wrappers.lambdaQuery(DpKeHu.class).notIn(DpKeHu::getId, ids));
        for (DpKeHu sysUserDepart : sysUserDeparts) {
            jdyDelete(sysUserDepart.getJdyId());

        }
        return BaseResult.success();
    }

    public void queryAndPush(String header, Integer index, List<String> ids) throws Exception {
        HashMap<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("start_index", index);
        paramMap.put("count", 1000);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + header);

//        String s = HttpRestUtils.get("https://api-sandbox.xiaoman.cn/v1/company/fields", Maps.newHashMap(), headers);
//        System.out.println(s);
        //String custmorResponse = HttpRestUtils.get(customersUrl, paramMap, headers);
        OkHttpClient cclient = new OkHttpClient();
        Request request1 = new Request.Builder()
                .url(customersUrl + getParams(paramMap)).addHeader("Authorization", "Bearer " + header).get()
                .build();
        Response execute1 = cclient.newCall(request1).execute();
        String custmorResponse = execute1.body().string();
        CustomerInfo customerInfo = JSONUtil.fromJson(custmorResponse, CustomerInfo.class);
        customerInfo.getData().getList().forEach(e -> {
            long companyId = e.getCompany_id();
            ids.add(companyId + "");
            Map map = new HashMap();
            map.put("company_id", companyId);
            map.put("format", 0);
            try {
                HttpHeaders newHeaders = new HttpHeaders();
                newHeaders.set("Authorization", "Bearer " + header);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(customerDetailUrl + getParams(map)).addHeader("Authorization", "Bearer " + header).get()
                        .build();
                Response execute = client.newCall(request).execute();
                // String custmoerDetailResponse = HttpRestUtils.get(customerDetailUrl+getParams(map), map, newHeaders);
                // log.info("custmoerDetailResponse"+custmoerDetailResponse);
                String body = execute.body().string();
                CustomerDetailInfo customerDetailInfo = JSONUtil.fromJson(body, CustomerDetailInfo.class);
                DpKeHu sysUserDepart = baseMapper.selectById(companyId + "");
                if (Objects.isNull(sysUserDepart)) {
                    addCustomer(customerDetailInfo);
                } else {
                    if (!Objects.equals(JSONUtil.toJson(customerDetailInfo.getData()),sysUserDepart.getData())) {
                        updateCustomer(sysUserDepart, customerDetailInfo);
                    }
                }
            } catch (Exception ex) {
                log.error("查询客户{}数据失败", companyId);
            }
        });
        if (CollectionUtil.isNotEmpty(customerInfo.getData().getList())) {
            queryAndPush(header, 1 + index, ids);
        }
    }

    private void updateCustomer(DpKeHu sysUserDepart, CustomerDetailInfo customerDetailInfo) throws IOException {
        HashMap<String, Object> param = getParam();
        XMUserReqDto xmUserReqDto = buidXMUserReqDto(customerDetailInfo);
        CustomerFieldsDTO customerFieldsDTO = new CustomerFieldsDTO();
        customerFieldsDTO.setGswz(xmUserReqDto.getGswz());
        customerFieldsDTO.setKhid(xmUserReqDto.getCustomer_no());
        customerFieldsDTO.setGsmc(xmUserReqDto.getCustomer_name());
        customerFieldsDTO.setGsjc(xmUserReqDto.getCustomer_abbreviation());
        customerFieldsDTO.setGjdq(xmUserReqDto.getMonther_land());
        customerFieldsDTO.setKhly(xmUserReqDto.getCustomer_orign());
        customerFieldsDTO.setKhxj(xmUserReqDto.getCustomer_stage());
        customerFieldsDTO.setKhbq(xmUserReqDto.getCustomer_label());
        customerFieldsDTO.setKhfz(xmUserReqDto.getGroup());
        customerFieldsDTO.setGjr(xmUserReqDto.get_widget_1694629005949());
        param.put("data", xmUserReqDto);
        param.put("data_id", sysUserDepart.getJdyId());
        sysUserDepart.setData(JSONUtil.toJson(customerDetailInfo.getData()));
        baseMapper.updateById(sysUserDepart);
        String post = HttpRestUtils.post(update_api, param, getJdyHeaders());
        log.info("表单修改结果{}", post);
    }

    private void addCustomer(CustomerDetailInfo customerDetailInfo) throws IOException {
        HashMap<String, Object> param = getParam();
        XMUserReqDto xmUserReqDto = buidXMUserReqDto(customerDetailInfo);
        CustomerFieldsDTO customerFieldsDTO = new CustomerFieldsDTO();
        customerFieldsDTO.setGswz(xmUserReqDto.getGswz());
        customerFieldsDTO.setKhid(xmUserReqDto.getCustomer_no());
        customerFieldsDTO.setGsmc(xmUserReqDto.getCustomer_name());
        customerFieldsDTO.setGsjc(xmUserReqDto.getCustomer_abbreviation());
        customerFieldsDTO.setGjdq(xmUserReqDto.getMonther_land());
        customerFieldsDTO.setKhly(xmUserReqDto.getCustomer_orign());
        customerFieldsDTO.setKhxj(xmUserReqDto.getCustomer_stage());
        customerFieldsDTO.setKhbq(xmUserReqDto.getCustomer_label());
        customerFieldsDTO.setKhfz(xmUserReqDto.getGroup());
        customerFieldsDTO.setGjr(xmUserReqDto.get_widget_1694629005949());
        param.put("data", customerFieldsDTO);
        String post = HttpRestUtils.post(add_api, param, getJdyHeaders());
        HashMap hashMap = JSONUtil.fromJson(post, HashMap.class);
        log.info("表单新增结果{}", post);
        DpKeHu userDepart = new DpKeHu();
        userDepart.setId(customerDetailInfo.getData().getCompany_id() + "");
        userDepart.setJdyId(((JSONObject) hashMap.get("data")).getString("_id"));
        userDepart.setData(JSONUtil.toJson(customerDetailInfo.getData()));
        baseMapper.insert(userDepart);

    }



    private XMUserReqDto buidXMUserReqDto(CustomerDetailInfo customerDetailInfo) {
        XMUserReqDto xmUserReqDto = new XMUserReqDto();
        CustomerDetailInfo.DataBean data = customerDetailInfo.getData();
        List<CustomerDetailInfo.DataBean.CustomersBean> customers = data.getCustomers();
        //基本资料
        buildXmUserReqDtoBaseData(xmUserReqDto, customerDetailInfo);
        HashMap<String, List<XMUserReqDto.ContactBean>> hashMap = Maps.newHashMap();
        hashMap.put("value",new ArrayList<>());
        xmUserReqDto.setContact(hashMap);
        return xmUserReqDto;
    }

    private void buildXmUserReqDtoBaseData(XMUserReqDto xmUserReqDto, CustomerDetailInfo customerDetailInfo) {
        CustomerDetailInfo.DataBean data = customerDetailInfo.getData();
        List<CustomerDetailInfo.DataBean.CompanyBean> company = data.getCompany();
        List<CustomerDetailInfo.DataBean.CompanyBean.FieldsBean> fieldsBeans = company.stream().flatMap(entry -> entry.getFields().stream()).collect(Collectors.toList());
        //fieldsBeans.addAll(customerDetailInfo.getData().getExternal_field_data());
        Map<String, String> fieldMap = fieldsBeans.stream().collect(Collectors.toMap(CustomerDetailInfo.DataBean.CompanyBean.FieldsBean::getId, CustomerDetailInfo.DataBean.CompanyBean.FieldsBean::getValue, (a, b) -> a));
        System.out.println(JSONUtil.toJson(fieldMap));
        xmUserReqDto.setCtreat_time(getParaMap(data.getArchive_time()));
        xmUserReqDto.setYxcp(getParaMap(fieldMap.get("907068638533")));

        xmUserReqDto.setGswz(getParaMap(fieldMap.get("homepage")));
        xmUserReqDto.setAddress(getParaMap(fieldMap.get("address")));
        xmUserReqDto.setCustomer_name(getParaMap(fieldMap.get("name")));
        xmUserReqDto.setCustomer_abbreviation(getParaMap(fieldMap.get("short_name")));
        String country = String.valueOf(getParaMap(fieldMap.get("country")));

        xmUserReqDto.setMonther_land(getParaMap(customerDetailInfo.getData().getCountry_name()));
        xmUserReqDto.setCustomer_no(getParaMap(customerDetailInfo.getData().getSerial_id()));
        List<XMUserReqDto.LogoBean> logoBeans = new ArrayList<>();
        XMUserReqDto.LogoBean logoBean = new XMUserReqDto.LogoBean();
        logoBean.setUrl(getParaMap(fieldMap.get("homepage")));
        logoBeans.add(logoBean);
        HashMap<String, List<XMUserReqDto.LogoBean>> hashMap = Maps.newHashMap();
        hashMap.put("value",logoBeans);
        xmUserReqDto.setLogo(hashMap);
        //xmUserReqDto.setFirst_area(StringUtils.isBlank(String.valueOf(fieldMap.get("4685536191540")))?null:getParaMap(filterFh(fieldMap.get("4685536191540"))));
        xmUserReqDto.setGroup(getParaMap(fieldMap.get("group_id")));
        xmUserReqDto.setCustomer_stage(getParaMap(fieldMap.get("star")));
        xmUserReqDto.setCustomer_nature(getParaMap(fieldMap.get("biz_type")));
        xmUserReqDto.setCustomer_orign(getParaMap(fieldMap.get("origin")));
        xmUserReqDto.setCustomer_attribution(getParaMap(fieldMap.get("")));
        String cus_tag = customerDetailInfo.getData().getTag().stream().map(CustomerTag::getTag_name).collect(Collectors.joining("|"));
        xmUserReqDto.setProduct_customer_label(getParaMap(cus_tag));
        List<CustomerOwner> customerOwners = customerDetailInfo.getData().getOwner();
        //业务员
        List<XMUserReqDto.AffiliatedSalespersonBean> affiliatedSalespersonBeans = new ArrayList<>();
        XMUserReqDto.AffiliatedSalespersonBean affiliatedSalespersonBean = new XMUserReqDto.AffiliatedSalespersonBean();
        String name = "";
        for (CustomerOwner e:
                customerOwners ) {
            affiliatedSalespersonBean = new XMUserReqDto.AffiliatedSalespersonBean();
            affiliatedSalespersonBean.setName(getParaMap(e.getName()));
            affiliatedSalespersonBean.setUsername(getParaMap(e.getNickname()));
            affiliatedSalespersonBeans.add(affiliatedSalespersonBean);
            name = e.getNickname();
        }
        xmUserReqDto.setAffiliated_salesperson(getParaMap(name));
        xmUserReqDto.setCustomer_label(getParaMap(fieldMap.get("cus_tag")));
        xmUserReqDto.setCustomer_nature(getParaMap(fieldMap.get("17995147088")));
        xmUserReqDto.setPhone(getParaMap(fieldMap.get("1990331804234")));
        xmUserReqDto.setHot_selling_series(getParaMap(fieldMap.get("1820018870213")));
        xmUserReqDto.setSurface_treatment(getParaMap(fieldMap.get("1820523514226")));
        xmUserReqDto.setRequired_profile_size(getParaMap(fieldMap.get("1990341612167")));
        xmUserReqDto.setApplication_scenario(getParaMap(fieldMap.get("1820034895295")));
        xmUserReqDto.setCustomer_focus(getParaMap(fieldMap.get("1820036315666")));
        xmUserReqDto.setSearch_fields(getParaMap(fieldMap.get("17385158304")));
        xmUserReqDto.setSearch_keyword_attributes(getParaMap(fieldMap.get("306672013382")));
        xmUserReqDto.setInquiry_type(getParaMap(fieldMap.get("306672013382")));
        xmUserReqDto.setFirst_inquiry_time(getParaMap(fieldMap.get("1575870621271")));
        xmUserReqDto.setBrowse_page(getParaMap(fieldMap.get("3457075506185")));
        xmUserReqDto.setBrowse_time(getParaMap(fieldMap.get("3457081849252")));
        xmUserReqDto.setDrainage_area(getParaMap(fieldMap.get("4685536191540")));
        xmUserReqDto.setAnnual_procurement_amount(getParaMap(fieldMap.get("annual_procurement")));
        xmUserReqDto.setPurchase_intention(getParaMap(fieldMap.get("intention_level")));
        xmUserReqDto.setLading_consignee(getParaMap(fieldMap.get("17995289702")));
        xmUserReqDto.setCompany_remarks(getParaMap(fieldMap.get("remark")));
        xmUserReqDto.setFirst_quest(getParaMap(fieldMap.get("4013377180063")));
        xmUserReqDto.setAnnual_procurement_volume(getParaMap(fieldMap.get("3144298072880")));
        xmUserReqDto.setImport_experience(getParaMap(fieldMap.get("3144323956870")));
        xmUserReqDto.setSales_city(getParaMap(fieldMap.get("1820374615887")));
        xmUserReqDto.setOrder_worry(getParaMap(fieldMap.get("4013469433675")));
        xmUserReqDto.setUser_feed_back(getParaMap(fieldMap.get("4013477508140")));
        xmUserReqDto.setUser_lost_why(getParaMap(fieldMap.get("18387648976")));
        xmUserReqDto.setUser_discount(getParaMap(fieldMap.get("1695297844587")));
        xmUserReqDto.setNew_old_platforms(getParaMap(fieldMap.get("20272197174")));
        xmUserReqDto.setFlow_in(getParaMap(fieldMap.get("22672416156")));
        xmUserReqDto.setProduct_id(getParaMap(fieldMap.get("306665134430")));
        xmUserReqDto.setProduct_line(getParaMap(fieldMap.get("9504965728")));
        xmUserReqDto.setSettlement_way(getParaMap(fieldMap.get("18364901310")));
        xmUserReqDto.setDjbl(getParaMap(fieldMap.get("54908918114093")));
        //年龄
        xmUserReqDto.setAge(getParaMap(fieldMap.get("18364901310")));
        try {
            if (CollectionUtil.isNotEmpty(data.getOwner())) {
                JdyReq jdyReq = new JdyReq();
                jdyReq.setApp_id(getAppId());
                jdyReq.setEntry_id("68d10826b10273b43196e208");
                jdyReq.setLimit(100);
                jdyReq.setFields(Arrays.asList("_widget_1758529574651", "_widget_1758529574650"));
                JdyReq.FilterBean filterBean = new JdyReq.FilterBean();
                filterBean.setRel("and");
                List<JdyReq.FilterBean.CondBean> cond = new ArrayList<>();
                JdyReq.FilterBean.CondBean a = new JdyReq.FilterBean.CondBean();
                a.setField("_widget_1758529574651");
                a.setType("text");
                a.setMethod("eq");
                a.setValue(customerOwners.stream().map(CustomerOwner::getNickname).collect(Collectors.toList()));
                cond.add(a);
                filterBean.setCond(cond);
                jdyReq.setFilter(filterBean);

                String s = jdyQueryAll(jdyReq);
                JSONArray jsonArray = (JSONArray) JSONUtil.fromJson(s, HashMap.class).get("data");
                if (jsonArray.size() > 0) {
                    List<DongPingPeopleDto> xiHuiPeopleDtos = jsonArray.stream().map(e -> JSONUtil.fromJson(JSONUtil.toJson(e), DongPingPeopleDto.class)).collect(Collectors.toList());
                    xmUserReqDto.set_widget_1694629005949(getParaMap(xiHuiPeopleDtos.stream().map(DongPingPeopleDto::get_widget_1758529574650).map(DongPingPeopleDto.CreatorBean::getUsername).collect(Collectors.toList())));
                }
            }
        } catch (Exception ex) {

        }
    }

}
